package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.enums.LoginTypeEnum;
import com.corpgovernment.api.organization.model.user.login.MbUserLoginVo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.organization.factory.LoginSourceServiceFactory;
import com.ctrip.corp.obt.auth.client.handler.token.JwtTokenHandler;
import com.ctrip.corp.obt.auth.core.token.OAuth2AccessToken;
import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码登录(与下面的TICKET登录配合使用，先APP扫描二维码，绑定好ticket)
 *
 * @author dlz
 * @since 2023/4/20
 */
@Service
@Slf4j
public class QRCodeLoginService extends AbstractLoginService {

    @Autowired
    private JwtTokenHandler jwtTokenHandler;
    @Autowired
    private LoginSourceServiceFactory loginSourceServiceFactory;

    @Override
    public UserLoginResponseVo login(MbUserLoginVo request) {
        String clientId = TenantContext.getClientId();
        String ticket = request.getTicket();
        if (clientId == null) {
            throw new CommonException(1031, "No client id was found");
        }
        if (StringUtils.isBlank(ticket)) {
            throw new CommonException(1033, "No ticket was found");
        }
        OAuth2AccessToken oAuth2AccessToken = jwtTokenHandler.createAccessTokenByTicket(
            clientId,
            ticket,
            false,
            new HashMap<>(Collections.singletonMap("source", request.getSource())));
        Map<String, Object> userInfoByAccessToken = jwtTokenHandler.getUserInfoByAccessToken(clientId, oAuth2AccessToken.getValue());
        BaseUserInfo userInfo = JsonUtils.convert(userInfoByAccessToken, BaseUserInfo.class);
        userInfo.setToken((String) userInfoByAccessToken.get("id"));
        UserLoginResponseVo response = new UserLoginResponseVo();
        response.setToken(oAuth2AccessToken.getValue())
            .setUserName(userInfo.getUserName())
            .setUid(userInfo.getUid())
            .setAccountName(userInfo.getAccountName())
            .setBgUser(userInfo.getBgUser())
            .setSource(userInfo.getSource())
            .setCid((String) userInfoByAccessToken.get("cid"))
            .setShowManage(false)
            .setExpiration(oAuth2AccessToken.getExpiration());
        return loginSourceServiceFactory.getLoginSourceService(request.getSource()).process(userInfo, response, LoginTypeEnum.QR_CODE);
    }

    @Override
    public String getLoginType() {
        return LoginTypeEnum.QR_CODE.toString();
    }
}
